import { dataList } from '@/api/data.js'
import choiceData from '@/api/choiceData'
// import matrixData from '@/api/matrixqueData'
import { mapMutations, mapGetters } from 'vuex'
export default {
  name: 'formData',
  data () {
    return {
      // form: [], // 用于存储单选题答题信息
      questions: [], // 用于存储单选题
      // matrixQues: matrixData, // 用于存储矩形量表题
      quesLength: 0,
      border: { div1: '', div2: '', div3: '', div4: '', div5: '', div6: '' },
      dialogVisible: false,
      submitStatus: false,
      regionChecked: [],
      currentProgress: [],
      percent: 0,
      currentPage: 1,
      totalPages: 3,
      basicIndex: {
        learn: 0,
        experience: 0,
        health: 0,
        burnout: 0,
        // anxious: 0,
        pressure: 0,
        ability: 0,
        // ba: 0,
        pa: 0,
        ea: 0,
        sa: 0,
        pb: 0,
        influence: 0,
        oi: 0,
        pi: 0,
        si: 0
      },
      avgIndex: {
        learn: 0,
        experience: 0,
        health: 0,
        burnout: 0,
        // anxious: 0,
        pressure: 0,
        ability: 0,
        // ba: 0,
        pa: 0,
        ea: 0,
        sa: 0,
        pb: 0,
        influence: 0,
        oi: 0,
        pi: 0,
        si: 0
      },
      stdIndex: {
        learn: 0,
        experience: 0,
        health: 0,
        burnout: 0,
        // anxious: 0,
        pressure: 0,
        ability: 0,
        // ba: 0,
        pa: 0,
        ea: 0,
        sa: 0,
        pb: 0,
        influence: 0,
        oi: 0,
        pi: 0,
        si: 0
      },
      bigred: [],
      midred: [],
      smallred: [],
      defau: [],
      smallblue: [],
      midblue: [],
      bigblue: [],
      sqlURL: 'http://localhost:3000/API',
      table: [],
      startTime: 0,
      submitTime: 0,
      lastTime: 0
    }
  },
  // 在Vue 挂载到DOM之后执行
  mounted () {
    // this.getData();
    this.getBaseData()
    this.$nextTick(() => {
      ['myTable1', 'myTable3', 'myTable4', 'myTable5', 'myTable6'].forEach(a => {
        this.findComponents(this.$refs[a], 'bigred', 1)
        this.bigred.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '20px'
          e.$el.querySelector('.el-radio__inner').style.height = '20px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'red'
          // e.$el.querySelector('.el-radio__input').addEventListener('change', function () {
          //   var inner = e.$el.querySelector('.el-radio__inner')
          //   if (e.$el.querySelector('.el-radio__input').checked) {
          //     inner.style.backgroundColor = 'red' // 将红色替换为你想要的颜色值
          //   } else {
          //     inner.style.backgroundColor = 'white' // 恢复默认背景色（可选）
          //   }
          // })
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'red'
        })
        this.findComponents(this.$refs[a], 'midred', 2)
        this.midred.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '18px'
          e.$el.querySelector('.el-radio__inner').style.height = '18px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'red'
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'red'
        })
        this.findComponents(this.$refs[a], 'smallred', 3)
        this.smallred.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '16px'
          e.$el.querySelector('.el-radio__inner').style.height = '16px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'red'
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'red'
        })
        this.findComponents(this.$refs[a], 'defau', 4)
        this.defau.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '14px'
          e.$el.querySelector('.el-radio__inner').style.height = '14px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'gray'
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'gray'
        })
        this.findComponents(this.$refs[a], 'bigblue', 7)
        this.bigblue.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '20px'
          e.$el.querySelector('.el-radio__inner').style.height = '20px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'blue'
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'blue'
        })
        this.findComponents(this.$refs[a], 'midblue', 6)
        this.midblue.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '18px'
          e.$el.querySelector('.el-radio__inner').style.height = '18px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'blue'
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'blue'
        })
        this.findComponents(this.$refs[a], 'smallblue', 5)
        this.smallblue.forEach(function (e) {
          e.$el.querySelector('.el-radio__inner').style.width = '16px'
          e.$el.querySelector('.el-radio__inner').style.height = '16px'
          e.$el.querySelector('.el-radio__inner').style.borderColor = 'blue'
          //   e.$el.querySelector('.el-radio__inner').style.backgroundColor = 'blue'
        })
      })
      // 在这里访问 $el 属性并修改样式
      //   const radioComponent = this.$refs.customRadio

      //   // 获取内部圆圈元素
      //   const innerCircle = radioComponent.$el.querySelector('.el-radio__inner')

      //   // 修改样式属性
      //   innerCircle.style.width = '20px' // 设置圆圈的宽度
      //   innerCircle.style.height = '20px' // 设置圆圈的高度
      //   innerCircle.style.backgroundColor = 'red' // 设置圆圈的颜色
    })
    // window.addEventListener('scroll', this.progressBar)
    window.addEventListener('click', this.getStartTime)
  },
  computed: {
    ...mapGetters({
      form: 'getForm',
      matrixQues: 'getMatrixData',
      timeCount: 'getTimeCount'
    }),
    basic () {
      return this.form
    }
  },
  watch: {
    basic: {
      handler (val) {
        for (var i = 0; i < val.length; i++) {
          if (val[i].answer !== '' && this.currentProgress.indexOf(i) === -1) {
            this.currentProgress.push(i)
          }
        }
      },
      deep: true
    },
    // 监听矩形量表题
    'matrixQues': {
      handler (val) {
        let i = 24
        for (let element of Object.values(this.matrixQues)) {
          for (let key of Object.keys(element)) {
            if (element[key].status !== '' && this.currentProgress.indexOf(i) === -1) {
              console.log(element[key].title)
              this.currentProgress.push(i)
            }
            i++
          }
        }
      },
      deep: true
    },
    // 设置进度条百分比
    currentProgress (newVal, oldVal) {
      const num = parseInt(newVal.length * 100 / this.quesLength)
      this.$refs.current.style.height = num + 'px'
      this.percent = num
    }
  },
  methods: {
    ...mapMutations([
      'setBasicIndex',
      'setStdIndex',
      'setAvgIndex',
      'setForm',
      'setMatrixData',
      'setTimeCount'
    ]),
    // 找组件
    findComponents (component, targetClass, type) {
      switch (type) {
        case 1:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.bigred.push(component)
          }
          if (component instanceof Element && component.children && component.children.length > 0) {
            for (const child of component.children) {
              this.findComponents(child, targetClass, type)
            }
          } else if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          // greenRadios.push(...childRadios);
          //   }
          //   if (component.$children && component.$children.length > 0) {
          //     for (const childComponent of component.$children) {
          //       this.findComponents(childComponent, targetClass, type)
          //     }
          //   }
          break
        case 2:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.midred.push(component)
          }
          if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          break
        case 3:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.smallred.push(component)
          }
          if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          break
        case 4:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.defau.push(component)
          }
          if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          break
        case 5:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.smallblue.push(component)
          }
          if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          break
        case 6:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.midblue.push(component)
          }
          if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          break
        case 7:
          if (component.$el && component.$el.classList && component.$el.classList.contains(targetClass)) {
            this.bigblue.push(component)
          }
          if (component.$children && component.$children.length > 0) {
            for (const childComponent of component.$children) {
              this.findComponents(childComponent, targetClass, type)
            }
          }
          break
      }
    },
    getStartTime () {
      this.startTime = new Date().getTime()
      window.removeEventListener('click', this.getStartTime)
    },
    // 获取数据
    getData () {
      dataList().then(res => {
        this.questions = res.data.msg
        // console.log(this.questions)
        // form 对象初始化
        const length = this.questions.length
        // 得到矩形量表题的总小题数
        var matrixLength = 0
        for (let element of Object.values(this.matrixQues)) {
          matrixLength += Object.keys(element).length
        }
        // 总题数赋值
        this.quesLength = length + matrixLength
        if (this.form.length === 0) {
          for (let i = 0; i < length + matrixLength; i++) {
            this.form.push({
              id: parseInt(i) + 1,
              answer: ''
            })
          }
        }
        if (this.form.length > this.quesLength) {
          this.form = this.form.slice(0, this.quesLength)
        }
      })
    },
    getBaseData () {
      this.questions = choiceData
      // console.log(this.questions)
      // form 对象初始化
      const length = this.questions.length
      // 得到矩形量表题的总小题数
      var matrixLength = 0
      for (let element of Object.values(this.matrixQues)) {
        matrixLength += Object.keys(element).length
      }
      // 总题数赋值
      this.quesLength = length + matrixLength
      for (let i = 0; i < length + matrixLength; i++) {
        this.form.push({
          id: parseInt(i) + 1,
          answer: ''
        })
      }
    },
    // progressBar () { // 更新进度条
    //   if (!!document.documentElement.scrollTop && document.documentElement.scrollTop > 0) {
    //     this.$refs.progress.style.top = document.documentElement.scrollTop - 50 + 'px'
    //   }
    // },
    submit () { // 提交
      // 将矩形量表题答案赋值给form
      // eslint-disable-next-line no-constant-condition
      if (true || this.checkPageFilled() === 0) {
        this.submitTime = new Date().getTime()
        this.lastTime = parseInt((this.submitTime - this.startTime) / 1000)
        this.setTimeCount(this.lastTime)
        var i = this.questions.length
        for (let element of Object.values(this.matrixQues)) {
          for (let key of Object.keys(element)) {
            this.form[i].answer = element[key].status
            i++
          }
        }
        // console.log(this.form)
        this.getBasicIndex()
        this.getTable()
        this.submitToMySQL()
      // })
      } else {
        this.$msgbox.alert('您第' + this.checkPageFilled() + '页没有全部完成', '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        // 3秒后关闭消息框
        setTimeout(() => {
          this.$msgbox.close()
        }, 2500)
      }
    },
    // 根据form数据获取基础指标
    getBasicIndex () {
      this.basicIndex.learn = Number((this.getIndexByArr([15, 16, 18, 19])).toFixed(2))

      this.basicIndex.experience = Number((this.getIndexByArr([1, 11, 12, 13, 14])).toFixed(2))

      this.basicIndex.burnout = Number((this.getMatrixIndex(5)).toFixed(2))
      // this.basicIndex.anxious = Number((this.getMatrixIndex(7)).toFixed(2))
      this.basicIndex.pressure = Number((this.getMatrixIndex(6)).toFixed(2))
      var healthval = 5 - (this.basicIndex.burnout + this.basicIndex.pressure) / 2
      this.basicIndex.health = Math.round(healthval * 100) / 100
      // this.basicIndex.ba = Number((this.getMatrixIndex(2)).toFixed(2))
      this.basicIndex.pa = Number((this.getMatrixIndex(3)).toFixed(2))
      this.basicIndex.ea = Number((this.getMatrixIndex(4)).toFixed(2))
      this.basicIndex.sa = Number((this.getIndexByArr([2, 6, 17, 18, 21, 22, 23])).toFixed(2))
      var abilityval = (this.basicIndex.pa + this.basicIndex.ea + this.basicIndex.sa) / 3
      this.basicIndex.ability = Math.round(abilityval * 100) / 100

      this.basicIndex.pb = Number((this.getMatrixIndex(5)).toFixed(2))

      this.basicIndex.oi = Number((this.getIndexByArr([7])).toFixed(2))
      this.basicIndex.pi = Number((this.getIndexByArr([4, 5, 20])).toFixed(2))
      this.basicIndex.si = Number((this.getIndexByArr([8, 9])).toFixed(2))
      var influenceval = (this.basicIndex.oi + this.basicIndex.pi + this.basicIndex.si) / 3
      this.basicIndex.influence = Math.round(influenceval * 100) / 100

      this.transValue()
    },
    // 数据提交数据库
    submitToMySQL () {
      this.$axios.post(this.sqlURL + '/createAnswer', {
        id: 0,
        singlechoice: this.getSingleChoice(),
        table1: this.table[0],
        table2: this.table[1],
        table3: this.table[2],
        table4: this.table[3],
        table5: this.table[4],
        // table6: this.table[5],
        // table7: this.table[6],
        learn: this.basicIndex.learn,
        experience: this.basicIndex.experience,
        health: this.basicIndex.health,
        burnout: this.basicIndex.burnout,
        // anxious: this.basicIndex.anxious,
        pressure: this.basicIndex.pressure,
        ability: this.basicIndex.ability,
        // ba: this.basicIndex.ba,
        pa: this.basicIndex.pa,
        ea: this.basicIndex.ea,
        sa: this.basicIndex.sa,
        pb: this.basicIndex.pb,
        influence: this.basicIndex.influence,
        oi: this.basicIndex.oi,
        pi: this.basicIndex.pi,
        si: this.basicIndex.si,
        timeCount: this.lastTime
      }).then(res => {
        this.$axios.get(this.sqlURL + '/getAnswers').then(res => {
          var data = res.data[0]
          Object.keys(this.$basicIndex).forEach((key) => {
            this.$avgIndex[key] = Number(data['avg' + key].toFixed(2))
            var stdTemp = Number(data['stdDev' + key].toFixed(2))
            if (stdTemp === 0) {
              this.$stdIndex[key] = Number((this.basicIndex[key] * 0.99).toFixed(2))
            } else {
              this.$stdIndex[key] = Number(((this.basicIndex[key] - this.$avgIndex[key]) / stdTemp * 0.99 + 2.5).toFixed(2))
            }
          })
          // 上传到vuex
          this.setBasicIndex(this.basicIndex)
          this.setAvgIndex(this.$avgIndex)
          this.setStdIndex(this.$stdIndex)
          this.setForm(this.form)
          this.setMatrixData(this.matrixQues)
          this.$message.success({
            message: '提交成功',
            duration: 3000
          })
          // 跳转2D显示
          this.$router.push({
            path: '/2D'
          })
        })
      }
      )
    },
    getSingleChoice () {
      let single = ''
      for (let i = 0; i < this.questions.length; i++) {
        single += this.form[i].answer
        single += ','
      }
      return single
    },
    getTable () {
      this.table = []
      for (let j = 1; j < 6; j++) {
        var ans = ''
        for (let i = 0; i < this.form.length; i++) {
          if (typeof this.form[i].answer === 'number' && this.form[i].answer > 100 && parseInt(this.form[i].answer / 100) === j) {
            ans += this.form[i].answer
            ans += ','
            // console.log('第'+i+'题答案是'+this.form[i].answer+'标准分是'+this.getStandardValue(this.form[i].answer).toString)
          }
        }
        this.table.push(ans)
      }
    },
    transValue () {
      this.$basicIndex.learn = this.basicIndex.learn
      this.$basicIndex.experience = this.basicIndex.experience
      this.$basicIndex.health = this.basicIndex.health
      this.$basicIndex.burnout = this.basicIndex.burnout
      // this.$basicIndex.anxious = this.basicIndex.anxious
      this.$basicIndex.pressure = this.basicIndex.pressure
      this.$basicIndex.ability = this.basicIndex.ability
      // this.$basicIndex.ba = this.basicIndex.ba
      this.$basicIndex.pa = this.basicIndex.pa
      this.$basicIndex.ea = this.basicIndex.ea
      this.$basicIndex.sa = this.basicIndex.sa
      this.$basicIndex.pb = this.basicIndex.pb
      this.$basicIndex.influence = this.basicIndex.influence
      this.$basicIndex.oi = this.basicIndex.oi
      this.$basicIndex.pi = this.basicIndex.pi
      this.$basicIndex.si = this.basicIndex.si
    },
    getStandardValue (str) {
      if (str === '') {
        return 0
      } else if (typeof str === 'string') {
        var val = str.substring(str.length - 2, str.length - 1)
        var total = str.substring(str.length - 1)
        return 5 * (val - 1) / (total - 1)
      } else if (typeof str === 'number') {
        var val1 = parseInt((str % 100) / 10)
        var total1 = parseInt(str % 10)
        return 5 * (val1 - 1) / (total1 - 1)
      } else {
        console.log('没取到标准分数')
        return 0
      }
    },
    // 非矩阵数据获取
    getIndexByArr (arr) {
      var tot = 0
      for (let i = 0; i < arr.length; i++) {
        tot += this.getStandardValue(this.form[arr[i]].answer)
      }
      if (tot / arr.length) {
        return tot / arr.length
      } else return 0
    },
    getMatrixIndex (num) {
      var count = 0
      var sum = 0
      // console.log(this.form[122].answer)
      // console.log(parseInt(this.form[122].answer/100))
      // console.log(this.form[122].answer > 100 && parseInt(this.form[122].answer/100) == 7)
      for (let i = 0; i < this.form.length; i++) {
        if (this.form[i].answer > 100 && parseInt(this.form[i].answer / 100) === num) {
          count++
          sum += this.getStandardValue(this.form[i].answer)
          // console.log('第'+i+'题答案是'+this.form[i].answer+'标准分是'+this.getStandardValue(this.form[i].answer).toString)
        }
      }
      if (count === 0) {
        return 0
      } else {
        return sum / count
      }
    },
    msgBox (message) { // 弹框提示
      this.$msgbox({
        title: '系统提示',
        message,
        showCancelButton: false,
        confirmButtonText: '确定',
        showClose: false,
        customClass: 'winClass',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            done()
          }
        }
      })
    },
    handleCurrentChange (page) {
      window.scrollTo(0, 0)
      // if (this.checkPageFilled(this.currentPage)[0] === 1) {
      // } else {
      //   this.$msgbox.alert('您第' + this.checkPageFilled(this.currentPage)[1] + this.checkPageFilled(this.currentPage)[2] + '页没有全部完成', '提示', {
      //     confirmButtonText: '确定',
      //     callback: action => {
      //     }
      //   })
      //   // 3秒后关闭消息框
      //   setTimeout(() => {
      //     this.$msgbox.close()
      //   }, 2500)
      // }
      this.currentPage = page
      // if (page > this.currentPage) {
      //   if (this.checkPageFilled(this.currentPage)) {
      //     this.currentPage = page
      //   } else {
      //     // 找到第一个未填写的题目，跳转到那里
      //     for (let i = this.currentPage; i <= this.totalPages; i++) {
      //       if (!this.checkPageFilled(i)) {
      //         this.currentPage = i
      //         break
      //       }
      //     }
      //   }
      // } else {
      // }
    },
    checkPageFilled () {
      // 编写逻辑来检查指定页面的题目是否都已填写
      for (let i = 0; i < this.questions.length; i++) {
        if (this.form[i].answer === '') {
          return 1
        }
      }
      for (let i = 0; i < this.matrixQues.question25.length; i++) {
        if (this.matrixQues.question25[i].status === '') { return 2 }
      }
      for (let i = 0; i < this.matrixQues.question27.length; i++) {
        if (this.matrixQues.question27[i].status === '') { return 2 }
      }
      for (let i = 0; i < this.matrixQues.question28.length; i++) {
        if (this.matrixQues.question28[i].status === '') { return 3 }
      }
      for (let i = 0; i < this.matrixQues.question29.length; i++) {
        if (this.matrixQues.question29[i].status === '') { return 3 }
      }
      for (let i = 0; i < this.matrixQues.question30.length; i++) {
        if (this.matrixQues.question30[i].status === '') { return 3 }
      }
      return 0
    }
  }
}
